package com.study.cacheManager;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.study.constant.CacheConstant;
import com.study.convention.errorCode.BaseErrorCode;
import com.study.convention.exception.RemoteException;
import com.study.convention.result.Result;
import com.study.dao.entity.TGroup;
import com.study.dao.mapper.TGroupMapper;
import com.study.dto.resp.ShortLinkGroupCountQueryRespDTO;
import com.study.feignClient.GroupShortLinkClient;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author canace
 * @version 1.0
 * @description 分组信息缓存管理器
 * @date 2024/1/28 19:51
 */

@Component
@RequiredArgsConstructor
public class GroupCacheManager {

    private final TGroupMapper groupMapper;

//    @Qualifier("com.study.feignClient.GroupShortLinkClient")
//    private final GroupShortLinkClient groupShortLinkClient;

    /**
     * 根据gid获取分组信息
     *
     * @param gid 分组id
     * @return 分组信息
     */
    @Cacheable(cacheManager = CacheConstant.REDIS_CACHE_MANAGER, cacheNames = CacheConstant.GROUP_INFO_BY_GID_CACHE_NAME, key = "#gid")
    public TGroup getGroupByGid(String gid) {
        LambdaQueryWrapper<TGroup> tGroupLambdaQueryWrapper = Wrappers.lambdaQuery(TGroup.class)
                .eq(TGroup::getGid, gid)
                .eq(TGroup::getDelFlag, 0);
        return groupMapper.selectOne(tGroupLambdaQueryWrapper);
    }

    /**
     * 根据用户名获取分组列表
     *
     * @param username 用户名
     * @return 分组列表
     */
    @Cacheable(cacheManager = CacheConstant.REDIS_CACHE_MANAGER, cacheNames = CacheConstant.GROUP_LIST_BY_USERNAME_CACHE_NAME, key = "#username")
    public List<TGroup> getGroupListByUsername(String username) {
        LambdaQueryWrapper<TGroup> tGroupLambdaQueryWrapper = Wrappers.lambdaQuery(TGroup.class)
                .eq(TGroup::getDelFlag, 0)
                .eq(TGroup::getUsername, username)
                .orderByDesc(TGroup::getSortOrder)
                .orderByDesc(TGroup::getUpdateTime);
//        List<TGroup> tGroups = groupMapper.selectList(tGroupLambdaQueryWrapper);
//        // 使用feign调用project微服务，获取当前用户短链接分组中有多少个短链接
//        Result<List<ShortLinkGroupCountQueryRespDTO>> listResult = groupShortLinkClient.listGroupShortLinkCount(tGroups.stream().map(TGroup::getGid).toList());
//        // 如果返回值为空或者code不为0
//        if (ObjectUtil.isEmpty(listResult) || !"0".equals(listResult.getCode())) {
//            throw new RemoteException(BaseErrorCode.REMOTE_ERROR);
//        }
//        // 将上面的集合转为Map，便于后续查找对应值
//        Map<String, Integer> map = listResult.getData().stream().collect(Collectors.toMap(ShortLinkGroupCountQueryRespDTO::getGid, ShortLinkGroupCountQueryRespDTO::getShortLinkCount));
//        // 结果封装返回
//        return tGroups.stream().peek(t -> t.setShortLinkCount(map.getOrDefault(t.getGid(), 0))).toList();
        // 不把短链接数量放入缓存，一直从redis中读取时反序列错误，暂时不知道原因
        return groupMapper.selectList(tGroupLambdaQueryWrapper);
    }

    /**
     * 清除gid缓存
     *
     * @param gid 分组id
     */
    @CacheEvict(cacheManager = CacheConstant.REDIS_CACHE_MANAGER, cacheNames = CacheConstant.GROUP_INFO_BY_GID_CACHE_NAME, key = "#gid")
    public void delCacheGroupByGid(String gid) {
        // 该方法只是清除缓存，不做其他操作
    }

    /**
     * 清除用户名分组缓存
     *
     * @param username 用户名
     */
    @CacheEvict(cacheManager = CacheConstant.REDIS_CACHE_MANAGER, cacheNames = CacheConstant.GROUP_LIST_BY_USERNAME_CACHE_NAME, key = "#username")
    public void delCacheGroupListByUsername(String username) {
        // 该方法只是清除缓存，不做其他操作
    }
}
